import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import 'package:flutter_wisave/widgets/AppColors.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';

class MessageDetailPage extends StatefulWidget {
  // final int noticeId;
  final String title;
  final String content;

  MessageDetailPage({Key? key, required this.content, required this.title})
      : super(key: key);

  @override
  State<MessageDetailPage> createState() => _MessageDetailPageState();
}

class _MessageDetailPageState extends State<MessageDetailPage>
    with SingleTickerProviderStateMixin {
  final NetworkService _networkService = NetworkService();
  late WebViewController _webViewController;
  // late String title = '';
  // late String content = '';
  bool isLoading = true;
  String errorMessage = '';
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _networkService.setupInterceptors(context);
    _initWebView();
    // _loadData();
    _loadWebViewContent();
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  Future<void> _initWebView() async {
    late final PlatformWebViewControllerCreationParams params;
    if (WebViewPlatform.instance is WebKitWebViewPlatform) {
      params = WebKitWebViewControllerCreationParams(
        allowsInlineMediaPlayback: true,
        mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
      );
    } else {
      params = const PlatformWebViewControllerCreationParams();
    }

    final WebViewController controller =
        WebViewController.fromPlatformCreationParams(params);

    controller
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageStarted: (String url) {
            print('页面开始加载: $url');
            _startLoadingTimer();
          },
          onPageFinished: (String url) {
            print('页面加载完成: $url');
            setState(() {
              isLoading = false;
            });
            _timer?.cancel();
          },
          onWebResourceError: (WebResourceError error) {
            print('加载错误: ${error.description}');
            setState(() {
              errorMessage = '加载失败: ${error.description}';
              isLoading = false;
            });
            _timer?.cancel();
          },
        ),
      );

    _webViewController = controller;

    // 尝试加载一个简单的HTML字符串
    try {
      await _webViewController
          .loadHtmlString('<html><body><h1>没有数据</h1></body></html>');
    } catch (e) {
      print('加载测试页面时出错: $e');
      setState(() {
        errorMessage = '初始化WebView失败: $e';
        isLoading = false;
      });
    }
  }

  void _startLoadingTimer() {
    _timer = Timer(const Duration(seconds: 10), () {
      if (isLoading) {
        setState(() {
          errorMessage = '加载超时，请检查网络连接或重试';
          isLoading = false;
        });
      }
    });
  }

  // Future<void> _loadData() async {
  //   try {
  //     final result = await _fetchData();
  //     if (result['code'] == 200 && result['data'] != null) {
  //       setState(() {
  //         title = result['data']['noticeTitle'] ?? '';
  //         content = result['data']['noticeContent'] ?? '';
  //         _loadWebViewContent();
  //       });
  //     } else {
  //       setState(() {
  //         errorMessage = '数据加载失败: ${result['msg']}';
  //       });
  //     }
  //   } catch (e) {
  //     setState(() {
  //       errorMessage = '数据加载错误: $e';
  //     });
  //   }
  // }

  void _loadWebViewContent() {
    if (widget.content.isNotEmpty) {
      print('正在加载HTML内容');
      Future.delayed(Duration(milliseconds: 100), () async {
        try {
          String styledContent = '';
          if (AppColors.isDarkMode)
            styledContent = '''
          <html>
          <head>
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
              <style>
                  body { 
                      font-size: 18px; 
                      margin: 0 20px; 
                      color: #ffffff;
                  }
                  img { 
                      max-width: 100%; 
                      height: auto; // 确保图片响应式
                  }
              </style>
          </head>
          <body>
              ${widget.content}
          </body>
          </html>
          ''';
          await _webViewController.loadHtmlString(styledContent);
          if (!AppColors.isDarkMode)
            styledContent = '''
          <html>
          <head>
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
              <style>
                  body { 
                      font-size: 18px; 
                      margin: 0 20px; 
                      color: #000000;
                  }
                  img { 
                      max-width: 100%; 
                      height: auto; // 确保图片响应式
                  }
              </style>
          </head>
          <body>
              ${widget.content}
          </body>
          </html>
          ''';
          await _webViewController.loadHtmlString(styledContent);
        } catch (e) {
          print('加载HTML内容时出错: $e');
          setState(() {
            errorMessage = '加载内容失败: $e';
            isLoading = false;
          });
        }
      });
    } else {
      print('内容为空');
      setState(() {
        errorMessage = '没有可显示的内容';
      });
    }
  }

  // Future<Map<String, dynamic>> _fetchData() async {
  //   try {
  //     final response =
  //         await _networkService.get('/system/notice/${widget.noticeId}');
  //     if (response.statusCode == 200) {
  //       return response.data;
  //     } else {
  //       throw Exception('steeloutday Failed to load data');
  //     }
  //   } catch (e) {
  //     print('steeloutday Error in _fetchData: $e');
  //     rethrow;
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent, // 状态栏颜色
    ));

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        backgroundColor: Colors.transparent,
        flexibleSpace: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/home/home_topbg.png'),
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),
      body: Stack(
        children: [
          if (errorMessage.isNotEmpty)
            Center(child: Text(errorMessage))
          else if (isLoading)
            const Center(child: CircularProgressIndicator())
          else
            WebViewWidget(controller: _webViewController),
        ],
      ),
    );
  }
}
